package com.xebest.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.thoughtworks.xstream.XStream;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.SupplyChainConfig;
import com.xebest.constant.XeConstans;
import com.xebest.util.DateUtil;
import com.xebest.util.msg.XeVenOrderMsg;
import com.xebest.web.model.*;
import com.xebest.web.service.SupplyChainService;
import com.xebest.web.service.XeVenOrderService;
import com.xebest.web.view.ErpUserInfo;
import com.xescm.gateway.Client;
import com.xescm.gateway.Request;
import com.xescm.gateway.Response;
import com.xescm.gateway.constant.Constants;
import com.xescm.gateway.constant.HttpHeader;
import com.xescm.gateway.constant.HttpSchema;
import com.xescm.gateway.enums.Method;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 供应链操作service
 * @author: 阮承志
 * @createTime: 2017年7月12日 下午02:58:58
 * @history:
 */
@Service
public class SupplyChainServiceImpl implements SupplyChainService{

    private static final Logger log = LoggerFactory.getLogger(SupplyChainService.class);//日志记录类
    @Autowired
    private SupplyChainConfig supplyChainConfig;//供应链信息
    @Autowired
    private XeVenOrderService xeVenOrderService;
    @Autowired
    private XeBaseUtil xeBaseUtil;
    /**
     * 调用供应链取消实发接口
     * @author: 阮承志
     * @createTime: 2017年7月12日 下午02:58:58
     * @history:
     * @param orderId
     * @return void
     * @throws Exception void
     */
    @Override
    public boolean cancelOrder(String orderId,String storeId) throws Exception{
        //封装供应链信息
        Map<String,String> map = new HashMap<String, String>();
        map.put("appkey",supplyChainConfig.getAppKey());
        map.put("secret",supplyChainConfig.getSecret());
        map.put("requestTime",DateUtil.getDate(new Date()));
        map.put("fromSYS",supplyChainConfig.getFromsys());
        map.put("method","cancelOrder");
        map.put("customerCode",storeId);
        map.put("requestContent",orderId);
        Map<String, String> headers = new HashMap<String, String>();
        //（必填）根据期望的Response内容类型设置
        headers.put(HttpHeader.HTTP_HEADER_ACCEPT, "application/json");
        Request request = new Request(Method.POST_FORM, HttpSchema.HTTP + supplyChainConfig.getAddress(),supplyChainConfig.getCancelOrderUrl(),supplyChainConfig.getAppKey(),supplyChainConfig.getSecret(), Constants.DEFAULT_TIMEOUT);
        request.setHeaders(headers);
        request.setBodys(map);
        log.info("供应链取消订单推送数据为 :{}",JSON.toJSON(request));
        long start = System.currentTimeMillis();
        Response response = Client.execute(request);
        long end = System.currentTimeMillis();
        log.info("调用供应链取消接口的响应内容:{},调用接口耗时:{}"+response.getBody().toString(),(end-start));
        JSONObject obj = JSONObject.fromObject(xml2JSON(response.getBody().toString()));
        log.info("响应码:"+obj.get("code").toString()+"");
        if (XeConstans._SEND_200.equals(obj.get("code").toString())) {
            return false;
        } else if ("503".equals(obj.get("code").toString())){
            return false;
        } else {
            return true;
        }
    }
    /**
     * 调用供应链推送实发
     * @author: 阮承志
     * @createTime: 2017年7月12日 下午02:58:58
     * @history:
     * @param orderId
     * @param orderRefundList
     * @return void
     * @throws Exception void
     */
    @Override
    public void insertSupplyChainOrder(XeVenOrderInfoEntity orderInfo, List<Map<String, Object>> orderRefundList,String ipAddress,ErpUserInfo userInfo) throws Exception {

        String xml = getOrders(orderInfo,orderRefundList);
        //封装供应链信息
        Map<String,String> map = new HashMap<String, String>();
        map.put("appkey",supplyChainConfig.getAppKey());
        map.put("secret",supplyChainConfig.getSecret());
        map.put("requestTime",DateUtil.getDate(new Date()));
        map.put("fromSYS",supplyChainConfig.getFromsys());
        map.put("method","getTransportOrder");
        map.put("requestContent",xml);
        Map<String, String> headers = new HashMap<String, String>();
        //（必填）根据期望的Response内容类型设置
        headers.put(HttpHeader.HTTP_HEADER_ACCEPT, "application/json");
        Request request = new Request(Method.POST_FORM, HttpSchema.HTTP + supplyChainConfig.getAddress(),supplyChainConfig.getPushOrderUrl(),supplyChainConfig.getAppKey(),supplyChainConfig.getSecret(), Constants.DEFAULT_TIMEOUT);
        log.info("请求头信息为 :{}", JSON.toJSONString(request));
        request.setHeaders(headers);
        request.setBodys(map);
        long start = System.currentTimeMillis();
        Response response = Client.execute(request);
        long end = System.currentTimeMillis();
        log.info("调用供应链推送订单接口的响应内容:{},调用接口耗时:{}",response.getBody().toString(),(end-start));
        this.xeVenOrderService.insertMqLog("erpOrder-confirmSendNum", "TMS_"+orderInfo.getOrderId(), response.getBody().toString() , userInfo, ipAddress, "TMS推送实发");
        JSONObject obj = JSONObject.fromObject(xml2JSON(response.getBody().toString()));
        log.info("响应码:"+obj.get("code").toString()+"");
        if (!obj.get("code").toString().equals(XeConstans._SEND_200)) {
            throw new RuntimeException(XeVenOrderMsg.ERROR);
        }
    }
    /**
     * 调用供应链判断是否发货
     * @author: 阮承志
     * @createTime: 2017年7月26日 下午5:58:58
     * @history:
     * @param orderId
     * @return void
     * @throws Exception void
     */
    @Override
    public boolean judgeSendGood(String storeId,String orderId) throws Exception{
        Map<String,String> map = new HashMap<String, String>();
        map.put("appkey",supplyChainConfig.getAppKey());
        map.put("secret",supplyChainConfig.getSecret());
        map.put("requestTime",DateUtil.getDate(new Date()));
        map.put("fromSYS",supplyChainConfig.getFromsys());
        map.put("method","getTransportStatus");
        map.put("customerOrderCode",orderId);
        map.put("customerCode",storeId);
        log.info("查询供应链物流状态参数为 :{}", JSON.toJSONString(map));
        Map<String, String> headers = new HashMap<String, String>();
        //（必填）根据期望的Response内容类型设置
        headers.put(HttpHeader.HTTP_HEADER_ACCEPT, "application/json");
        Request request = new Request(Method.POST_FORM, HttpSchema.HTTP + supplyChainConfig.getAddress(),supplyChainConfig.getJudgeSendGoodUrl(),supplyChainConfig.getAppKey(),supplyChainConfig.getSecret(), Constants.DEFAULT_TIMEOUT);
        request.setHeaders(headers);
        request.setBodys(map);
        // 调用供应链取消接口服务端
        long start = System.currentTimeMillis();
        Response response = Client.execute(request);
        long end = System.currentTimeMillis();
        log.info("调用供应链物流接口的响应内容:{},调用接口耗时:{}",response.getBody().toString(),(end-start));
        JSONObject obj = JSONObject.fromObject(xml2JSON(response.getBody().toString()));
        log.info("响应内容:"+obj+"响应码:"+obj.get("code").toString()+"");
        boolean flag = true;
        if (XeConstans._SEND_200.equals(obj.get("code").toString())) {
            if (obj.containsKey("result")) {
            	com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(obj.get("result").toString());
            	Object object = parseObject.get("transportStateList");
            	if (object instanceof com.alibaba.fastjson.JSONObject) {
            		return false;
            	} else {
            		return true;
            	}
            	/*JSONArray parseArray = JSON.parseArray();
                if (null != parseArray && parseArray.size() != 1) {
            	SupplyChainResult result = JSON.parseObject(obj.get("result").toString(), SupplyChainResult.class);
            	if (null != result.getTransportStateList() && result.getTransportStateList().size() != 1) {
            		flag = true;
                } else {
                    flag = false;
                }*/
            } else {
                flag = false;
            }
        } else {
            flag = true;
        }
        return flag;
    }


    /**
     * 封装传输供应链实体
     * @param orderInfo
     * @return
     */
    private String getOrders(XeVenOrderInfoEntity orderInfo,List<Map<String, Object>> orderRefundList) {
        Orders orders = new Orders();
        //订单信息
        Order order = new Order();
        List<orderDetail> list = new ArrayList<orderDetail>();
        //订单明细信息
        order.setCustCode(orderInfo.getStoreId());//仓库编码
        order.setCustName(orderInfo.getStoreId());
        order.setCustOrderCode(orderInfo.getOrderId());
        order.setOrderTime(DateUtil.getDate(orderInfo.getCreateDate()));
        order.setOrderType(60);
        order.setBusinessType(600);
        order.setConsignorCode(orderInfo.getStoreId());

//        order.setConsigneeCode(orderInfo.getUserId());
        order.setConsigneeName(orderInfo.getStoreName());
        order.setConsigneeContact(orderInfo.getCaConsignee());
        order.setConsigneePhone(orderInfo.getCaPhone());
        order.setConsigneeProvince(xeBaseUtil.getAreaName(Integer.parseInt(orderInfo.getCaProvinceId())));
        order.setConsigneeCity(xeBaseUtil.getAreaName(Integer.parseInt(orderInfo.getCaCityId())));
        order.setConsigneeCounty(xeBaseUtil.getAreaName(Integer.parseInt(orderInfo.getCaAreaId())));
        order.setConsigneeAddress(orderInfo.getCaStreet());
        order.setWeight(null);
        order.setQuantity(null);

        for (int i = 0; i < orderInfo.getOrderInfoDetailList().size(); i++) {
            XeVenOrderInfoDetailEntity orderInfoDetail = orderInfo.getOrderInfoDetailList().get(i);
            orderDetail orderDetail = new orderDetail();
            orderDetail.setGoodsCode(orderInfoDetail.getProSku());
            orderDetail.setGoodsName(orderInfoDetail.getProName());
            orderDetail.setGoodsSpec(orderInfoDetail.getSpecValue());

            //有修改实发  重量和数量为修改的值   没有则为购买数量
            if (null != orderRefundList && orderRefundList.size() > XeConstans._XE_ZERO) {
                for (int j = 0; j < orderRefundList.size(); j++) {
                    Map<String, Object> orderRefund = orderRefundList.get(j);
                    if (orderRefund.get("itemId").toString().equals(orderInfoDetail.getItemId())) {
                        //新标准重量 = 原标准重量*实发/购买
                        BigDecimal weight = orderInfoDetail.getNormWeight()
                                .multiply(new BigDecimal(orderRefund.get("buyNums").toString()).subtract(new BigDecimal(orderRefund.get("rejectNums").toString())))
                                .divide(new BigDecimal(orderRefund.get("buyNums").toString()), 2, RoundingMode.HALF_UP);
                        if (orderInfoDetail.getPricingType().equals(XeConstans._XE_TWO)) { //按数量算
                            orderDetail.setQuantity(new BigDecimal(orderRefund.get("buyNums").toString()).subtract(new BigDecimal(orderRefund.get("rejectNums").toString())));
                        }
                        log.info("订单明细ID为 :{},实发标准重量为 :{}",orderRefund.get("itemId").toString(),weight);
                        orderDetail.setWeight(weight);
                    } else {
                        if (orderInfoDetail.getPricingType().equals(XeConstans._XE_TWO)) {//按数量算
                            orderDetail.setQuantity(orderInfoDetail.getPurchaseNum());
                        }
                        orderDetail.setWeight(orderInfoDetail.getNormWeight());
                    }
                }
            } else {
                if (orderInfoDetail.getPricingType().equals(XeConstans._XE_TWO)) { //按重量算
                    orderDetail.setQuantity(orderInfoDetail.getPurchaseNum());
                }
                orderDetail.setWeight(orderInfoDetail.getNormWeight());
            }
            orderDetail.setUnit(orderInfoDetail.getProUnit());
            orderDetail.setUnitPrice(orderInfoDetail.getProPrice());
            list.add(orderDetail);
        }
        order.setOrderDetails(list);
        orders.setOrder(order);
        log.info("推送供应链订单数据为 :{}", JSON.toJSONString(orders));
        XStream xs = new XStream();
        xs.setMode(XStream.NO_REFERENCES);
        String top = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";
        xs.processAnnotations(new Class[]{Orders.class,Order.class,orderDetail.class});
        return top + xs.toXML(orders);
    }
    public static String xml2JSON(String xml) {
        return new XMLSerializer().read(xml).toString();
    }

    public static void main(String[] args) {
        XStream xs = new XStream();
        xs.setMode(XStream.NO_REFERENCES);

        Orders orders = new Orders();
        Order order = new Order();
        order.setCustCode("123213131");
        List<orderDetail>  list = new ArrayList<orderDetail>();
        orderDetail orderDetail = new orderDetail();
        orderDetail orderDetail2 = new orderDetail();
        orderDetail2.setGoodsName("香瓜");
        orderDetail.setGoodsName("西瓜");
        orderDetail.setGoodsCode("1231231");
        list.add(orderDetail);
        list.add(orderDetail2);
        order.setOrderDetails(list);
        orders.setOrder(order);
        String top = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n";
        xs.processAnnotations(new Class[]{Orders.class,Order.class,orderDetail.class});
        String xml =top + xs.toXML(orders);
        System.out.println(xml);
        JSONObject jsonObject = JSONObject.fromObject(xs.fromXML(xml));
        JSONObject order1 = JSONObject.fromObject(jsonObject.get("order"));
        System.out.println(order1.get("custCode"));

        final BigDecimal[] aa = {new BigDecimal("0")};
        List<BigDecimal> list1 = new ArrayList<BigDecimal>();
        list1.add(new BigDecimal("1"));
        list1.add(new BigDecimal("2"));
        list1.add(new BigDecimal("3"));
        list1.add(new BigDecimal("4"));
        list1.stream().forEach(a -> {
            System.out.println(a);
            if (a.compareTo(new BigDecimal("3")) == 0) {
                System.out.println("------进入条件-----");
            } else {
                aa[0] = aa[0].add(a);

            }
        });
        System.out.println(aa[0]);
    }
}
